package com.server.modules.api.service.impl;

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.server.common.utils.StringUtils;
import com.server.modules.api.service.IBaseJPushService;
import org.apache.log4j.Logger;

import java.util.Map;

public class BaseJPushService implements IBaseJPushService {

    Logger logger = Logger.getLogger(BaseJPushService.class);

    private JPushClient pushClient;
    private String secretKey;
    private String apiKeyString;
    private boolean open = true;

    public BaseJPushService() {
    }

    BaseJPushService(String secretKey, String apiKey) {
        this.pushClient = new JPushClient(secretKey, apiKey);
    }

    BaseJPushService(String secretKey, String apiKey, boolean open) {
        this.pushClient = new JPushClient(secretKey, apiKey,3);
        this.open=open;
    }
    BaseJPushService(String secretKey, String apiKey, String open) {
        this.pushClient = new JPushClient(secretKey, apiKey,3);
        boolean isOpen=false;
        if(StringUtils.isNotBlank(open)&&"1".equals(open)){
            isOpen=true;
        }
        this.open=isOpen;
    }

    @Override
    public void pushNotification2One(String content, String alias,
                                     Map<String, String> extras) {
//		pushAndroidNotification2One(content, alias,extras);
//		pushIosNotification2One(content, alias, extras);
        content = getSendContent(content, extras);
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder().setAlert(content)
                        .addPlatformNotification(AndroidNotification.newBuilder().addExtras(extras).build())
                        .addPlatformNotification(IosNotification.newBuilder().addExtras(extras).setSound("happy").build()).build()).setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        sendPush(pushPayload);
    }

    @Override
    public void pushAndroidNotification2One(String content, String alias,
                                            Map<String, String> extras) {
        content = getSendContent(content,extras);
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.android(content, "", extras))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        sendPush(pushPayload);
    }

    @Override
    public void pushIosNotification2One(String content, String alias,
                                        Map<String, String> extras) {
        content = getSendContent(content,extras);
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(content)
                                .addExtras(extras)
                                .build())
                        .build())
                .setMessage(Message.content(content))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        sendPush(pushPayload);
    }

    @Override
    public void pushAndroidNotificationAll(String content,
                                           Map<String, String> extras) {
        //处理推送内容的长度
        content = getSendContent(content,extras);
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(content)
                                .addExtras(extras)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        sendPush(pushPayload);
    }

    @Override
    public void pushIosNotificationAll(String content,
                                       Map<String, String> extras) {
        content = getSendContent(content,extras);
        PushPayload pushPayload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(content)
                                .addExtras(extras)
                                .build())
                        .build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
        sendPush(pushPayload);
    }

    @Override
    public void pushAll(String content, Map<String, String> extras) {
        pushAndroidNotificationAll(content,extras);
        pushIosNotificationAll(content,extras);
    }

    private void sendPush(PushPayload pushPayload){
        if(open) {
            try {
                pushClient.sendPush(pushPayload);
//					PushResult result = pushClient.sendPush(pushPayload);
//					System.out.println(result.toString());
            } catch (APIConnectionException e) {
                //这里不再打印推送异常，比较多的异常就是某设备未绑定设备造成
                logger.error("APIConnectionException 推送异常: \n"+ pushPayload.toJSON());
            } catch (APIRequestException e) {
                logger.error("APIRequestException 推送异常: \r\n"+ pushPayload.toJSON());
            }
        }
    }

    /**
     * 处理推送内容长度
     *
     * @param @param content
     * @param @param extras
     * @param @return
     * @return String
     * @author tj
     * @Create 2014年11月5日 上午10:05:22
     * @Modify {修改人1} {修改时间1} {修改目的1}
     */
    private static String getSendContent(String content,Map<String, String> extras){
        //处理推送内容的长度
        if(extras.get("u")!=null){
            String url = extras.get("u");
            int contentLen = 54-url.length()/3;
            if(content.length()>contentLen){
                content = content.substring(0,contentLen);
            }
        }else if(extras.get("e")!=null){
            String eid = extras.get("e");
            int contentLen = 54-eid.length()/3;
            if(content.length()>contentLen){
                content = content.substring(0,contentLen);
            }
        }else{
            if(content.length()>54){
                content = content.substring(0,54);//固定字数
            }
        }
        return content;
    }

    public JPushClient getPushClient() {
        return pushClient;
    }

    public void setPushClient(JPushClient pushClient) {
        this.pushClient = pushClient;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getApiKeyString() {
        return apiKeyString;
    }

    public void setApiKeyString(String apiKeyString) {
        this.apiKeyString = apiKeyString;
    }

}
